package com.bolt.auth.security.auth.server.component;

import com.bolt.auth.admin.api.feign.RemoteUserService;
import com.bolt.auth.admin.api.sys.entity.LoginLogEntity;
import com.bolt.auth.admin.api.sys.entity.UserEntity;
import com.bolt.auth.security.common.model.AuthUserDetails;
import com.bolt.auth.security.common.utils.SecurityUtils;
import com.bolt.common.web.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Service
@Slf4j
public class  CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        AuthUserDetails userDetails = SecurityUtils.getUser(authentication);
        LocalDateTime now = LocalDateTime.now();
        //写入登入记录信息
        LoginLogEntity userLoginLog = new LoginLogEntity();
        userLoginLog.setUser(new UserEntity(userDetails.getUserId()));
        userLoginLog.setLogonTime(now);
        userLoginLog.setRemoteAddr(request.getRemoteAddr());
        userLoginLog.setRemoteHost(request.getRemoteHost());
        userLoginLog.setRemotePort(request.getRemotePort());
        userLoginLog.setUserAgent(request.getHeader("User-Agent"));
        userLoginLog.setXforwardFor(RequestUtil.getRemoteIpAddress(request));
        remoteUserService.saveUserLoginLog(userLoginLog);

        super.onAuthenticationSuccess(request, response, authentication);
    }
}

 